package com.woniuxy.coachweb.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.lang.Snowflake;
import com.woniuxy.coachmodel.dto.CoachLoginDto;
import com.woniuxy.coachmodel.form.*;
import com.woniuxy.coachmodel.param.*;
import com.woniuxy.coachservice.exception.CoachException;
import com.woniuxy.coachservice.service.CoachInfoService;
import com.woniuxy.core.model.Result;
import com.woniuxy.core.util.MyJwtUtil;
import com.woniuxy.core.util.PageInfo;
import com.woniuxy.util.MyOssUtil;
import com.woniuxy.util.MyRedisUtil;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 教练 前端控制器
 * </p>
 *
 * @author 冉杰
 * @since 2024-01-15
 */
@RestController
@RequestMapping("/coachInfo")
@Api(tags = "教练服务详细信息接口")
public class CoachInfoController {

    @Value("${server.port}")
    private int port;
    @Autowired
    private CoachInfoService coachInfoService;
    @Resource
    private MyOssUtil myOssUtil;
    @Resource
    private MyRedisUtil myRedisUtil;


    @GetMapping("/sendRegisterCode")
    @ApiOperation("发送注册手机号验证码接口")
    public Result sendRegisterCode(String phone) throws Exception {
        coachInfoService.sendRegisterCode(phone);
        return Result.success("发送验证码成功");
    }

    @PostMapping("/register")
    @ApiOperation("教练注册接口")
    public Result register(@RequestBody @Validated CoachRegisterForm form){
        CoachRegisterParam param = BeanUtil.toBean(form, CoachRegisterParam.class);
        coachInfoService.register(param);
        return Result.success("教练注册成功");
    }

    @PostMapping("/loginByAccountPass")
    @ApiOperation("教练账号密码登录接口")
    public Result loginByAccountPass(@RequestBody @Validated CoachLoginByAccountPassForm form,HttpServletResponse response, HttpServletRequest request){
        CoachLoginByAccountPassParam param = BeanUtil.toBean(form, CoachLoginByAccountPassParam.class);
        String ip = request.getRemoteAddr();
        String ipAddr = ip+":"+port;
        param.setIpAddr(ipAddr);
        CoachLoginDto dto = coachInfoService.loginByAccountPass(param);
        Map<String, Object> map = new HashMap<>();
        map.put("coachId",dto.getCoachId());
        String coachToken = MyJwtUtil.createCoachToken(map, 240);
        response.setHeader("token", coachToken);
        response.setHeader("Access-Control-Expose-Headers", "token");
        return Result.success("教练账号密码登录成功",dto);
    }

    @ApiOperation("发送登录验证码接口")
    @GetMapping("/sendLoginCode")
    public Result sendLoginPhoneCode(String phone) throws Exception {
        coachInfoService.sendLoginPhoneCode(phone);
        return Result.success("验证码发送成功");
    }

    @PostMapping("/loginByPhoneCode")
    @ApiOperation("手机验证登录接口")
    public Result loginByPhoneCode(@RequestBody @Validated CoachLoginByPhoneCodeForm form,HttpServletResponse response,HttpServletRequest request){
        CoachLoginByPhoneCodeParam param = BeanUtil.toBean(form, CoachLoginByPhoneCodeParam.class);
        String ip = request.getRemoteAddr();
        String ipAddr = ip+":"+port;
        param.setIpAddr(ipAddr);
        CoachLoginDto dto = coachInfoService.loginByPhoneCode(param);
        Map<String, Object> map = new HashMap<>();
        map.put("coachId",dto.getCoachId());
        String coachToken = MyJwtUtil.createCoachToken(map, 240);
        response.setHeader("token", coachToken);
        response.setHeader("Access-Control-Expose-Headers", "token");
        return Result.success("教练手机验证码登录成功",dto);
    }

    @ApiOperation("上传教练头像图片接口")
    @PostMapping("/upload.coach")
    public Result uploadCoachImage(MultipartFile uploadFile,@RequestHeader String token) throws Exception{
        String type = FileTypeUtil.getType(uploadFile.getInputStream());
        if (!type.equals("jpg")&&!type.equals("png")){
            throw new CoachException(20005,"图片格式异常");
        }
        String fileName = new Snowflake(1, 1).nextIdStr();
        fileName = fileName+"."+type;
        String url = myOssUtil.uploadFile(uploadFile.getInputStream(), fileName, "ranjie11");
        String refreshToken = myRedisUtil.get(token);
        Claims claims = MyJwtUtil.parseCoachToken(refreshToken);
        Integer coachId = Integer.parseInt(claims.get("coachId").toString());
        //保存头像地址到数据库
        coachInfoService.uploadCoachAvatar(url,coachId);
        return Result.success("上传教练图片成功",url);
    }
    @ApiOperation("修改教练头像图片接口")
    @PostMapping("/updateCoachImage.coach")
    public Result updateCoachImage(@RequestParam("image") MultipartFile file, @RequestHeader String token) throws IOException {
        UpdateCoachAvatarParam param = new UpdateCoachAvatarParam();
        Integer coachId = MyJwtUtil.getCoachIdByKey(token, "coachId");
        param.setCoachId(coachId);
        param.setImage(file);
        coachInfoService.updateCoachAvatar(param);
        return Result.success("修改教练图片成功");
    }
    /**
     *
     * @param uploadFile 图片文件
     * @param token
     * @return
     * @throws Exception
     */
    @ApiOperation("上传教练执照图片接口")
    @PostMapping("/uploadCoachLicense.coach")
    public Result uploadCoachLicense(MultipartFile uploadFile,@RequestHeader String token) throws Exception{
        String type = FileTypeUtil.getType(uploadFile.getInputStream());
        if (!type.equals("jpg")&&!type.equals("png")){
            throw new CoachException(20005,"图片格式异常");
        }
        String fileName = new Snowflake(1, 1).nextIdStr();
        fileName = fileName+"."+type;
        String url = myOssUtil.uploadFile(uploadFile.getInputStream(), fileName, "ranjie11");
        Integer coachId = MyJwtUtil.getCoachIdByKey(token, "coachId");
        //保存头像地址到数据库
        coachInfoService.uploadCoachLicense(url,coachId);
        return Result.success("上传教练图片成功",url);
    }

    /**
     *
     * @param form
     * @param token
     * @return
     */
    @PostMapping("/refine.coach")
    @ApiOperation("教练完善/修改个人简介接口")
    public Result refine(@RequestBody @Validated RefineForm form,@RequestHeader String token){
        Integer coachId = MyJwtUtil.getCoachIdByKey(token, "coachId");
        RefineParam param = BeanUtil.toBean(form, RefineParam.class);
        param.setCoachId(coachId);
        coachInfoService.refine(param);
        return Result.success("成功完善教练个人简介信息");
    }

    @GetMapping("/checkOldPass.coach")
    @ApiOperation("验证教练老密码接口")
    public Result checkOldPass(String oldPass, @RequestHeader String token) throws Exception {
        Integer coachId = MyJwtUtil.getCoachIdByKey(token, "coachId");
        coachInfoService.checkOldPass(oldPass,coachId);
        return Result.success("成功验证教练老密码");
    }

    @PostMapping("/updatePass.coach")
    @ApiOperation("教练修改密码接口")
    public Result updatePass(@RequestBody @Validated UpdateCoachPassForm form, @RequestHeader String token) throws Exception {
        Integer coachId = MyJwtUtil.getCoachIdByKey(token, "coachId");
        UpdateCoachPassParam param = BeanUtil.toBean(form, UpdateCoachPassParam.class);
        param.setCoachId(coachId);
        coachInfoService.updatePass(param);
        return Result.success("成功修改教练密码");
    }

    @PostMapping("/updateCoachPhone.coach")
    @ApiOperation("修改教练手机号码接口")
    public Result updateCoachPhone(@RequestBody @Validated UpdateCoachPhoneForm form,@RequestHeader String token){
        Integer coachId = MyJwtUtil.getCoachIdByKey(token, "coachId");
        UpdateCoachPhoneParam param = BeanUtil.toBean(form, UpdateCoachPhoneParam.class);
        param.setCoachId(coachId);
        coachInfoService.updateCoachPhone(param);
        return Result.success("成功修改教练手机号码");
    }

    @PostMapping("/disableCoach.api")
    @ApiOperation("禁用教练账号接口")
    public Result disableCoach(@RequestBody @Validated UpdateCoachStateForm form){
        coachInfoService.disableCoach(form);
        return Result.success("成功禁用教练账号");
    }
    /**
     *
     * @param form
     * @return 无
     */
    @PostMapping("/enableCoach.api")
    @ApiOperation("启用教练账号接口")
    public Result enableCoach(@RequestBody @Validated UpdateCoachStateForm form){
        coachInfoService.enableCoach(form);
        return Result.success("成功启用教练账号");
    }
    /**
     *
     * @param form
     * @return
     */
    @PostMapping("/auditCoach.api")
    @ApiOperation("同意认证教练账号接口")
    public Result auditCoach(@RequestBody @Validated UpdateCoachStateForm form){
        coachInfoService.auditCoach(form);
        return Result.success("成功审核教练账号");
    }

    @GetMapping("/refuseCoach.api")
    @ApiOperation("拒绝认证教练账号接口")
    public Result refuseCoach(Integer coachId,String message){
        coachInfoService.refuseCoach(coachId,message);
        return Result.success("成功拒绝认证教练账号");
    }
    @GetMapping("/viewPersonalInformation.coach")
    @ApiOperation("教练查看个人信息接口")
    public Result viewPersonalInformation(@RequestHeader String token){
        Integer coachId = MyJwtUtil.getCoachIdByKey(token, "coachId");
        CoachLoginDto dto = coachInfoService.viewPersonalInformation(coachId);
        return Result.success("成功查询个人信息",dto);
    }
    @PostMapping("/searchCoach.api")
    @ApiOperation("平台端按条件分页查询教练接口")
    public Result searchCoach(@RequestBody @Validated ApiSearchCoachForm form){
        PageInfo<CoachLoginDto> dtoPageInfo = coachInfoService.searchCoach(form);
        return Result.success("成功查询教练账号",dtoPageInfo);
    }

    @GetMapping("/searchCoachByCoachId")
    @ApiOperation("基于教练Id查询教练接口")
    public Result searchCoachByCoachId(Integer coachId){
        CoachLoginDto dto = coachInfoService.searchCoachByCoachId(coachId);
        return Result.success("成功查询教练账号",dto);
    }
    @GetMapping("/searchAllCoachByCoachIds")
    @ApiOperation("基于教练Ids查询所有教练接口")
    public Result searchAllCoachByCoachIds(List<Integer> coachIds){
        List<CoachLoginDto> dtos = coachInfoService.searchAllCoachByCoachIds(coachIds);
        return Result.success("成功查询所有教练账号",dtos);
    }
    @GetMapping("/searchCoachByCoachId.venue")
    @ApiOperation("商家基于教练Id查询已认证教练接口")
    public Result venueSearchCoachByCoachId(Integer coachId){
        CoachLoginDto dto = coachInfoService.venueSearchCoachByCoachId(coachId);
        return Result.success("成功查询所有教练账号",dto);
    }
    @GetMapping("/venueSearchCoach.venue")
    @ApiOperation("商家查询所有已认证教练接口")
    public Result venueSearchCoach(){
        List<CoachLoginDto> dtos = coachInfoService.venueSearchCoach();
        return Result.success("成功查询所有已认证教练账号",dtos);
    }
    @GetMapping("/userSearchCoach")
    @ApiOperation("用户查询所有已认证教练接口")
    public Result userSearchCoach(){
        List<CoachLoginDto> dtos = coachInfoService.venueSearchCoach();
        return Result.success("成功查询所有已认证教练账号",dtos);
    }
    @GetMapping("/searchCoachByVenueId")
    @ApiOperation("基于商家Id查询教练接口")
    public Result<List<CoachLoginDto>> searchCoachByVenueId(Integer venueId){
        List<CoachLoginDto> dtos = coachInfoService.findCoachByVenueId(venueId);
        return Result.success("成功查询所有教练账号",dtos);
    }
    /**
     *
     * @param token 商家登录token
     * @return
     */
    @GetMapping("/findCoach.venue")
    @ApiOperation("商家端查看自家教练")
    public Result findCoach(@RequestHeader String token){
        Integer venueId = MyJwtUtil.getVenueIdByKey(token, "venueId");
        List<CoachLoginDto> dtos = coachInfoService.findCoachByVenueId(venueId);
        return Result.success("成功查询所有教练账号",dtos);
    }

    @ApiOperation("商家分页查看自家教练")
    @GetMapping("/byPage.venue")
    public Result<PageInfo<CoachLoginDto>> byPage(Integer pageNum,Integer pageSize ,@RequestHeader String token){
        Integer venueId = MyJwtUtil.getVenueIdByKey(token, "venueId");
        PageInfo<CoachLoginDto> pageInfo = coachInfoService.byPage(pageNum,pageSize,venueId);
        return Result.success("商家分页查看自家教练成功",pageInfo);
    }







    












































}

